import 'package:get/get.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../../models/order.dart';
import '../../services/auth_service.dart';
import '../../services/order_service.dart';

class OrderLogic extends GetxController {
  final AuthService _authService = AuthService();
  final OrderService _orderService = OrderService();

  final RxList<Order> orderList = <Order>[].obs;
  final isLoading = true.obs;
  final isAdmin = false.obs;

  @override
  void onInit() {
    super.onInit();
    _checkIfAdmin();
    loadOrders();
  }

  Future<void> _checkIfAdmin() async {
    isAdmin.value = await _authService.isCurrentUserAdmin();
  }

  Future<void> loadOrders() async {
    isLoading.value = true;
    try {
      final userId = await _authService.getCurrentUserId();
      if (userId == null) {
        SmartDialog.showToast('用户未登录');
        return;
      }

      List<Order> orders;
      if (isAdmin.value) {
        // Admin can see all orders
        orders = await _orderService.getAllOrders();
      } else {
        // Regular users can only see their own orders
        orders = await _orderService.getOrdersByUserId(userId);
      }

      orderList.value = orders;
    } catch (e) {
      SmartDialog.showToast('加载订单失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  void goToOrderDetail(Order order) {
    Get.toNamed('/order-detail', arguments: order)?.then((result) {
      // 如果返回结果为true，表示需要刷新订单列表
      if (result == true) {
        loadOrders();
      }
    });
  }
}
